package com.bookstore.back.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bookstore.back.entity.UserLog;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Map;

/**
 * 用户日志Mapper接口
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Mapper
public interface UserLogMapper extends BaseMapper<UserLog> {

    /**
     * 获取用户统计信息
     */
    @Select("SELECT " +
            "COUNT(CASE WHEN log_type = 'login' THEN 1 END) AS loginCount, " +
            "COUNT(CASE WHEN log_type = 'operation' THEN 1 END) AS operationCount, " +
            "MAX(CASE WHEN log_type = 'login' THEN created_at END) AS lastLoginTime, " +
            "(" +
            "  SELECT ip_address FROM user_logs " +
            "  WHERE user_id = #{userId} AND log_type = 'login' " +
            "  ORDER BY created_at DESC LIMIT 1" +
            ") AS lastLoginIp " +
            "FROM user_logs WHERE user_id = #{userId}")
    Map<String, Object> getUserStats(@Param("userId") Long userId);

    /**
     * 记录用户登录日志
     */
    @Insert("INSERT INTO user_logs (user_id, log_type, ip_address, user_agent, created_at) " +
            "VALUES (#{userId}, 'login', #{ipAddress}, #{userAgent}, NOW())")
    int insertLoginLog(@Param("userId") Long userId,
                      @Param("ipAddress") String ipAddress,
                      @Param("userAgent") String userAgent);

    /**
     * 记录用户操作日志
     */
    @Insert("INSERT INTO user_logs (user_id, log_type, ip_address, user_agent, details, created_at) " +
            "VALUES (#{userId}, 'operation', #{ipAddress}, #{userAgent}, #{details}, NOW())")
    int insertOperationLog(@Param("userId") Long userId,
                          @Param("ipAddress") String ipAddress,
                          @Param("userAgent") String userAgent,
                          @Param("details") String details);

}
